package com.example.purchase.view.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.purchase.MyApplication;
import com.example.purchase.R;
import com.example.purchase.adapter.MainRecyclerViewAdapter;
import com.example.purchase.bean.BaseBean;
import com.example.purchase.bean.MainBean;
import com.example.purchase.databinding.ActivityMainBinding;
import com.example.purchase.network.RetrofitClient;
import com.example.purchase.network.service.HttpService;
import com.example.purchase.view.base.BaseActivity;
import com.google.android.material.navigation.NavigationView;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Predicate;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class MainActivity extends BaseActivity<ActivityMainBinding> implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    private Banner banner;
    private List<Integer> mImage = new ArrayList<>();        //存放图片地址集合
    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


//        String phone = sp.getString("phone","13018731726");
//        String role = sp.getString("role","false");
//        Log.e("TAG", "onBaseCreate: " + phone);
//        Log.e("TAG", "onBaseCreate: " + role);
        sp = getSharedPreferences("userMessage", Context.MODE_PRIVATE);
        Log.e("TAG", "onBaseCreate: " + token);
        if (sp.getString("role","").equals("false")){
            //隐藏Admin权限的内容
            dataBinding.navView.getMenu().findItem(R.id.admin).setVisible(false);
        }
        dataBinding.navView.setItemIconTintList(null);

        initImageView();

    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData() {
        dataBinding.swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                            initTimeOut();
                            dataBinding.swipeRefresh.setRefreshing(false);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    @Override
    protected void initEmpty() {

    }

    @Override
    protected void initClick() {
        dataBinding.top.setOnClickListener(this);
        dataBinding.headerMain.setOnClickListener(this);
        dataBinding.navView.setNavigationItemSelectedListener(this);
        dataBinding.search.setOnClickListener(this);
    }

    @Override
    protected void initTimeOut() {
        HttpService service = RetrofitClient.getInstance().getService(HttpService.class);
        service.getTicketList("中山","0","0","1",token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Predicate<BaseBean<List<MainBean>>>() {
                    @Override
                    public boolean test(BaseBean<List<MainBean>> listBaseBean) throws Throwable {
                        return String.valueOf(listBaseBean.getCode()).equals("200");
                    }
                }).subscribe(new Consumer<BaseBean<List<MainBean>>>() {
            @Override
            public void accept(BaseBean<List<MainBean>> listBaseBean) throws Throwable {
                dataBinding.recyclerView.setAdapter(new MainRecyclerViewAdapter(listBaseBean,getApplicationContext()));
                dataBinding.recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
            }
        });
    }

    //初始化Banner
    private void initImageView() {
        banner = findViewById(R.id.banner);

        mImage.add(R.mipmap.ic_banner);
        mImage.add(R.mipmap.ic_banner_2);
        mImage.add(R.mipmap.ic_banner_3);
        mImage.add(R.mipmap.ic_banner_4);

        banner.setAdapter(new BannerImageAdapter<Integer>(mImage) {
            @Override
            public void onBindView(BannerImageHolder holder, Integer data, int position, int size) {
                Glide.with(holder.itemView)
                        .load(data)
                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
                        .into(holder.imageView);
            }
        })
                .setIndicator(new CircleIndicator(this))
                .setIndicatorGravity(IndicatorConfig.Direction.CENTER);

        //点击时间 下标从0开始
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(Object data, int position) {
                Toast.makeText(MainActivity.this, "点击了第" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    //NavigationView Item 点击事件
    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_set:
                startActivity(new Intent(MainActivity.this,EditinfoActivity.class));
                break;
            case R.id.nav_order:
                startActivity(new Intent(MainActivity.this, FavoriteActivity.class).putExtra("type",MyApplication.ORDER_LIST));
                break;
            case R.id.nav_love:
                startActivity(new Intent(MainActivity.this, FavoriteActivity.class).putExtra("type",MyApplication.LOVE_LIST));
                break;
            case R.id.nav_order_admin:
                startActivity(new Intent(MainActivity.this, FavoriteActivity.class).putExtra("type",MyApplication.ADMIN_ORDER));
                break;
            case R.id.nav_ticket:
                startActivity(new Intent(MainActivity.this, TicketManageActivity.class));
                break;
            case R.id.nav_out:
                finish();
                break;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //避免跳转太快，侧滑栏还没收齐来，BUG视角
                    Thread.sleep(500);
                    dataBinding.drawerLayout.closeDrawers();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top:
                dataBinding.scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        dataBinding.scrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                dataBinding.scrollView.fullScroll(View.FOCUS_UP);
                            }
                        });
                    }
                });
                break;
            case R.id.header_main:
                dataBinding.drawerLayout.openDrawer(GravityCompat.END);
                break;
            case R.id.search:
                startActivity(new Intent(MainActivity.this,SearchActivity.class));
                break;
        }
    }

    @Override
    protected boolean isStatusBarEnabled() {
        return false;
    }

    @Override
    protected int getStatusBarColor() {
        return 0xFAFAFAFA;
    }
}